<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from 'echarts'
import { debounce } from '@/utils'

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'dark')
      this.chart.setOption({
        backgroundColor: 'transparent',
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['1月', '2月', '3月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
        },
        yAxis: {
          type: 'value'
        },
        grid: {
          top: 20,
          bottom: 20
        },
        series: [
          {
            data: [820, 932, 901, 934, 1290, 1330, 1320, 1290, 330, 10, 1290, 1330],
            type: 'line',
            color: '#5aaef4',
            areaStyle: { color: '#4783bd' },
            itemStyle: {
              normal: {
                lineStyle: {
                  color: '#5aaef4'
                }
              }
            }
          }
        ]
      })
    }
  }
}
</script>
